# = class.emails.rb - Email Helper Class
#
# See LICENSE.txt for licensing details.
#
# == Description
# This class allows us to watch and scan for emails that are being sent and parse those
# to make sure that CS is sending the emails correctly, in the expected format, and so
# forth.
#

require 'tmail'
require 'rexml/document'

class Emails
  def isEmailValid?(emailTo, emailType)
    $all_emails = Dir['c:/inetpub/mailroot/queue/*.eml']
    
    $all_emails.each {|x| 
      mail = TMail::Mail.load( x )       

      ## Only look at emails queued in the last 2 minutes
      t = Time.now - 120

      if (mail.date > t && mail.to[0] == emailTo)
        ## Check to make sure that the email does not contain any remaining [] elements
        m = mail.body.scan(/\[\w+?\]/)

        if (m.length == 0)
          ## Get the email body string from template and divide it into an array without the [] elements
          templateBodies = getEmailBody(emailType).split(/\[\w+?\]/)

          ## Check each chunk of text in the body template to make sure it exists in the outgoing email
          templateBodies.each { |b|
            if (mail.body.index(b) == 0)              
              return false
            end
          }
          
          return true
        else
            puts 'Body still contains email template item: ' + m[0]          
        end
      else
        if (mail.date <= t)
          puts 'Email sent too long ago at: ' + mail.date.to_s
        elsif (mail.to[0] != emailTo)
          puts 'Could not find an email in the queue folder with specified email'  
        end
      end
    }
    
    return false
  end
  
  def getEmailBody(emailType)
    if (@emails == nil || @emails.length == 0)
      open('resources/emails.xml') { |f| @emails = f.read  }
    end
    if (@emails.length == 0)
      return ''
    end
    
    doc = REXML::Document.new @emails 
    
    emailBody = REXML::XPath.first(doc, '//email[@emailType="' + emailType + '"]//body')
    emailBody = emailBody.to_s.mgsub([[/.*<body>/i, ''], [/.*<\/body>/i, '']])
    
    return emailBody     
  end
end
